<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <div>
        <!-- 搜索框 -->
        <el-row :gutter="20">
          <el-col :span="10">
            <el-input
              placeholder="请输入内容"
              v-model="userinfo.query"
              :clearable="true"
              ><el-button
                slot="append"
                icon="el-icon-search"
                @click="getuser"
              ></el-button></el-input
          ></el-col>
          <el-col :span="6"
            ><el-button type="primary" @click="dialogVisible = true"
              >添加</el-button
            ></el-col
          >
        </el-row>
        <!-- 添加用户对话框 -->
        <el-dialog
          title="添加用户"
          :visible.sync="dialogVisible"
          width="50%"
          @close="addclosed"
        >
          <el-form
            :model="addForm"
            :rules="addrules"
            ref="addForm"
            label-width="70px"
          >
            <el-form-item label="用户名" prop="username">
              <el-input v-model="addForm.username"></el-input>
            </el-form-item>
            <el-form-item label="密码" prop="password">
              <el-input v-model="addForm.password"></el-input>
            </el-form-item>
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="addForm.email"></el-input>
            </el-form-item>
            <el-form-item label="手机" prop="mobile">
              <el-input v-model="addForm.mobile"></el-input>
            </el-form-item>
          </el-form>
          <span slot="footer">
            <el-button @click="dialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="adduser">确定</el-button>
          </span>
        </el-dialog>
        <!-- 表格 -->
        <el-table :data="booklist" border stripe>
          <el-table-column label="索引" type="index"> </el-table-column>
          <el-table-column prop="username" label="姓名"> </el-table-column>
          <el-table-column prop="email" label="邮箱"> </el-table-column>
          <el-table-column prop="mobile" label="电话"> </el-table-column>
          <el-table-column prop="role_name" label="角色"> </el-table-column>
          <el-table-column label="状态">
            <template slot-scope="scope">
              <!-- {{ scope.row }} -->
              <el-switch
                v-model="scope.row.mg_state"
                active-color="#13ce66"
                inactive-color="#ff4949"
                @change="userStateChange(scope.row)"
              >
              </el-switch>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="190px">
            <template slot-scope="scope">
              <!-- 修改按钮 -->
              <el-button
                type="primary"
                icon="el-icon-edit"
                size="mini"
                @click="showdialog(scope.row.id)"
              ></el-button>
              <!-- 删除按钮 -->
              <el-button
                type="danger"
                icon="el-icon-delete"
                size="mini"
                @click="dalect(scope.row.id)"
              ></el-button>
              <!-- 分配角色按钮 -->
              <el-tooltip
                effect="dark"
                content="分配角色"
                placement="top"
                :enterable="false"
              >
                <el-button
                  type="warning"
                  icon="el-icon-setting"
                  size="mini"
                ></el-button>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>
        <!-- 修改用户信息对话框 -->
        <el-form
          :model="editForm"
          :rules="editFormrules"
          ref="editForm"
          label-width="70px"
        >
          <el-dialog
            title="修改用户信息"
            :visible.sync="dialogVisible11"
            width="50%"
            @close="editclosed"
          >
            <el-form-item label="用户名">
              <el-input v-model="editForm.username" disabled></el-input>
            </el-form-item>
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="editForm.email"></el-input>
            </el-form-item>
            <el-form-item label="手机" prop="mobile">
              <el-input v-model="editForm.mobile"></el-input>
            </el-form-item>
            <span slot="footer">
              <el-button @click="dialogVisible11 = false">取 消</el-button>
              <el-button type="primary" @click="editubfo">确 定</el-button>
            </span>
          </el-dialog>
        </el-form>
        <!-- 分页 -->
        <!-- - size-change：每页显示条数改变事件 -->
        <!-- - current-change：当前页改变事件 -->
        <!-- - current-page：当前页，指定的值为queryInfo.pagenum -->
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="userinfo.pagenum"
          :page-sizes="[1, 2, 5, 7]"
          :page-size="userinfo.pagesize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        >
        </el-pagination>
      </div>
    </el-card>
  </div>
</template>
<script>
export default {
  data: function() {
    // 自定义邮箱校验规则
    var checkemail = (rule, value, callback) => {
      const regemail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/
      if (regemail.test(value)) {
        // 合法邮箱
        return callback()
      }
      callback(new Error('请输入合法的邮箱'))
    }
    // 自定义手机号校验规则
    var checkmobile = (rule, value, callback) => {
      const regmobile = /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/
      if (regmobile.test(value)) {
        // 合法手机号
        return callback()
      }
      callback(new Error('请输入合法的手机号'))
    }
    return {
      dialogVisible: false,
      dialogVisible11: false,
      booklist: [],
      // 查询到的用户信息对象
      editForm: {},
      userinfo: {
        // 查询参数
        query: '',
        // 当前的页数
        pagenum: 1,
        // 当前每页显示多少条数据
        pagesize: 2
      },
      // total数据总数
      total: 0,
      addForm: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      // 校验
      addrules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码器', trigger: 'blur' },
          { min: 6, max: 15, message: '长度在 6 到 15 个字符', trigger: 'blur' }
        ],
        email: [{ validator: checkemail, trigger: 'blur' }],
        mobile: [{ validator: checkmobile, trigger: 'blur' }]
      },
      // 修改后验证对象
      editFormrules: {
        email: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { validator: checkemail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: checkmobile, trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    getuser: async function() {
      const { data: set } = await this.$http.get('users', {
        params: this.userinfo
      })
      // console.log(set)
      if (set.meta.status !== 200) {
        return this.$message.error('获取管理员列表失败！')
      }
      this.booklist = set.data.users
      this.total = set.data.total
    },
    // 监听 一个页面显示几个  改变事件
    handleSizeChange: function(newsize) {
      // console.log(newsize)
      this.userinfo.pagesize = newsize
      this.getuser()
    },
    // 监听 页码值 （选中的那一页并显示）改变事件
    handleCurrentChange: function(newpage) {
      // console.log(newpage)
      this.userinfo.pagenum = newpage
      this.getuser()
    },
    // 监听switchk开关切换事件
    userStateChange: async function(state) {
      // console.log(state)
      const { data: ret } = await this.$http.put(
        `users/${state.id}/state/${state.mg_state}`
      )
      // console.log(ret)
      if (ret.meta.status !== 200) {
        status.mg_state = !status.mg_state
        return this.$message.error('设置状态失败！')
      }
      this.$message.success('设置状态成功! ')
    },
    // 监听添加用户对话框的关闭事件
    addclosed: function() {
      // 表单重置
      this.$refs.addForm.resetFields()
    },
    // 点击按钮，添加新用户
    adduser: function() {
      // 用来判断用户输入的格式是否正确 如果正确valid返回一个true
      this.$refs.addForm.validate(async valid => {
        // console.log(valid)
        if (!valid) return
        const { data: res } = await this.$http.post('users', this.addForm)
        // console.log(res)
        if (res.meta.status !== 201) {
          return this.$message.error('添加用户失败!')
        }
        this.$message.success('添加用户成功！')
        this.dialogVisible = false
        // 重新渲染请求数据
        this.getuser()
      })
    },
    // 修改用户信息对话框
    showdialog: async function(id) {
      this.dialogVisible11 = true
      // console.log(id)
      const { data: res } = await this.$http.get('users/' + id)
      // console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error('获取数据失败')
      }
      this.editForm = res.data
      // console.log(this.editForm)
      // this.dialogVisible11 = true
    },
    // 监听修改用户对话框的关闭事件
    editclosed: function() {
      // 表单重置
      this.$refs.editForm.resetFields()
    },
    editubfo: function() {
      // 用来判断用户输入的格式是否正确 如果正确valid返回一个true
      this.$refs.editForm.validate(async valid => {
        // console.log(valid)
        if (!valid) return
        const { data: res } = await this.$http.put(
          'users/' + this.editForm.id,
          {
            email: this.editForm.email,
            mobile: this.editForm.mobile
          }
        )
        // console.log(res)
        if (res.meta.status !== 200) {
          return this.$message.error('更新用户失败!')
        }
        this.$message.success('更新用户成功！')
        this.dialogVisible11 = false
        // 重新渲染请求数据
        this.getuser()
      })
    },
    // 删除用户信息
    dalect: async function(id) {
      const confirm = await this.$confirm(
        '此操作将永久删除该文件, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(err => err)
      // console.log(confirm)
      // 如果用户确定删除，则返回值为confirm
      // 如果用户取消删除，则返回cancel
      if (confirm !== 'confirm') {
        return this.$message.info('已取消删除')
      }
      const { data: res } = await this.$http.delete('users/' + id)
      // console.log(res)
      if (res.meta.status !== 200) {
        return this.$$message.Error('删除失败')
      }
      this.$message.success('删除成功')
      this.getuser()
    }
  },
  // 生命周期
  created: function() {
    this.getuser()
  }
}
</script>
<style scoped>
.el-card {
  margin-top: 15px;
  box-shadow: 0 1px 1px rgb(0, 0, 0.1);
}
.el-table {
  margin-top: 15px;
  font-size: 12px;
}
.el-pagination {
  margin-top: 15px;
}
</style>
